package com.zhugang.week02;

/**
 * @program algorithms
 * @description: addTwoNumbers
 * @author: chanzhugang
 * @create: 2022/05/30 15:41
 */
public class AddTwoNumbers {

    /**
     * 2. 两数相加
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 开辟新链表，遍历原有两个链表，每个节点相加，余数插入新链表尾部，除数做为进位数（下个节点加上）
        ListNode dummyHead = new ListNode();
        ListNode tail = dummyHead;
        ListNode p1 = l1;
        ListNode p2 = l2;
        // 进位
        int carry = 0;
        while (p1 != null || p2 != null) {
            int sum = 0;
            if (p1 != null) {
                sum += p1.val;
                p1 = p1.next;
            }
            if (p2 != null) {
                sum += p2.val;
                p2 = p2.next;
            }
            if (carry != 0) {
                // 加上进位
                sum += carry;
            }
            tail.next = new ListNode(sum % 10);
            carry = sum / 10;
            tail = tail.next;
        }
        if (carry != 0) {
            // 最后一位节点相加后有进位
            tail.next = new ListNode(carry);
        }

        return dummyHead.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}